package cn.xhjava.crm.commons.exception;

import cn.xhjava.crm.commons.ReturnObject;
import cn.xhjava.crm.commons.SysContants;
import cn.xhjava.crm.commons.util.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author:   XiaHu
 * Date:     2023/6/27
 * <p>
 * 全局异常处理器
 */
// @Configuration
public class SysHandlerExceptionResolver implements HandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(SysHandlerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                         Exception e) {
        logger.error(ExceptionUtil.getStackTrace(e));
        //处理异常的代码实现
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();

        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(SysContants.RETURN_OBJECT_CODE_FAIL);
        returnObject.setMessage("系统忙，请稍后重试....");

        if (e instanceof Exception) {
            modelAndView.addObject(modelAndView);
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
